layui.use('table', function () {

    var table = layui.table;

    //第一个实例
    table.render({
        elem: "#demo"
        , url: '/findormitory'
        , method: 'post'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , limit: 7
        , id: 'testReload'
        , limits: [3, 5, 7]
        , cols: [[
            {field: 'pkId', width: 80, type: 'checkbox'},
            {field: 'area', width: 185, title: '区域', sort: true,},
            {field: 'buildingNo', width: 185, title: '楼号'},
            {field: 'buildingFloor', width: 185, title: '楼层'},
            {field: 'dormitoryName', width: 185, title: '宿舍名称', sort: true},
            {field: 'bedNumber', width: 185, title: '床位数量',hide:true},
            {field: 'bedNumbers', width: 185, title: '床位数量'},
            {field: 'dormSupervisor', width: 185, title: '宿舍主管'},
            {field: 'useStatus', width: 185, title: '宿舍是否被使用', sort: true},
            {field: 'createTime', width: 205, title: '创建时间', sort: true},
            {field: 'updateTime', width: 205, title: '修改时间'},
            {field: 'right', width: 140, title: '操作', toolbar: '#barDemo'},
        ]],
        done: function (res, curr, count){

            $("[data-field='useStatus']").children().each(function () {
                if ($(this).text() == '0') {
                    $(this).text("正常");
                }
                if ($(this).text() == '1') {
                    $(this).text("空闲");
                }
                if ($(this).text() == '2') {
                    $(this).text("保留");
                }
            });
        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        },
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        },
    });
    //升序降序后重新渲染
    table.on('sort(test)', function(obj) {
        table.reload('testReload', {
            initSort: obj
        });
    });
    table.reload('testReload', {});
    //表单数据重载
    var $ = layui.$,active = {
        reload : function (){
            var dormitoryName = $("#dormitoryName");
            var dormSupervisor = $("#dormSupervisor");
            var bedNumber = $("#bedNumber");
            var buildingFloor = $("#buildingFloor");
            var buildingNo = $("#buildingNo");
            var area = $("#region");
            //执行重载
            table.reload('testReload',{
                page: {
                    curr : 1 //重新从第一页开始
                },
                where:{
                    dormitoryName:dormitoryName.val(),
                    dormSupervisor:dormSupervisor.val(),
                    bedNumber:bedNumber.val(),
                    buildingFloor:buildingFloor.val(),
                    buildingNo:buildingNo.val(),
                    area:area.val(),
                }
            });
        }
    };
    $('.demoTable .layui-btn').on('click',function (){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    // //监听头工具事件
    table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
            ,data = checkStatus.data //获取选中的数据
            ,delList=[];
        for(var i=0;i<data.length;i++){
            delList.push(data[i].pkId);
        }
        var json={"pkIds":delList};
        switch(obj.event) {
            case 'add':
                layer.msg('添加');
                layer.open({
                    type: 1 //此处以iframe举例
                    , title: '班级信息录入表'
                    , area: ['800px', '650px']
                    , shade: 0
                    , maxmin: true
                    , content: $("#insertPage")
                })
                //区域楼号楼层下拉框
                $.ajax({
                    type:"post",
                    url:"/area",
                    contentType: "application/json;charset=utf-8",
                    dataType:"json",
                    success:function (regions) {
                        var $regiones="<option value=''>请选择</option>";
                        for(var i=0;i<regions.length;i++) {
                            $regiones+="<option value="+regions[i].area+">"+regions[i].area+"</option>"
                        }
                        $("select[name='inarea']").html($regiones);

                        //当select发生改变时
                        $("select[name='inarea']").change(function() {
                            $("#upbuildingNo").empty();
                            if ( $("select[name='inarea'] option:selected").text() == "A") {
                                var $QINGXUANZE ="<option>请选择</option>";
                                $("#inbuildingNo").append($QINGXUANZE);
                                for(let i = 1;i<=5;i++){
                                    var $data = $("<option >" + i + "号</option>");
                                    $("#inbuildingNo").append($data);
                                }
                            }
                            if ( $("select[name='inarea'] option:selected").text() == "B") {
                                var $QINGXUANZE ="<option>请选择</option>";
                                $("#inbuildingNo").append($QINGXUANZE);
                                for(let i = 6;i<=10;i++){
                                    var $data = $("<option >" + i+ "号</option>");
                                    $("#inbuildingNo").append($data);
                                }
                            }
                            if ( $("select[name='inarea'] option:selected").text() == "C") {
                                var $QINGXUANZE ="<option>请选择</option>";
                                $("#inbuildingNo").append($QINGXUANZE);
                                for(let i = 11;i<=15;i++){
                                    var $data = $("<option >" + i+ "号</option>");
                                    $("#inbuildingNo").append($data);
                                }
                            }
                            if ( $("select[name='inarea'] option:selected").text() == "D") {
                                var $QINGXUANZE ="<option>请选择</option>";
                                $("#inbuildingNo").append($QINGXUANZE);
                                for(let i = 16;i<=20;i++){
                                    var $data = $("<option >" + i+ "号</option>");
                                    $("#inbuildingNo").append($data);
                                }

                            }
                            layui.form.render('select');
                        })
                        $("select[name='inbuildingNo']").change(function() {
                            $("#inbuildingFloor").empty();
                            let buildingNo = $("#buildingNo").val();
                            $.get("",function(){
                                var $QINGXUANZE ="<option>请选择</option>";
                                $("#inbuildingFloor").append($QINGXUANZE);
                                for(let i = 1;i<=12;i++){
                                    var $data = $("<option >" +i + "层</option>");
                                    $("#inbuildingFloor").append($data);
                                }
                                layui.form.render('select');
                            })
                        })
                    },error:function (error) {
                        layer.msg("添加请求失败1");
                    }
                });
                $("#insertdormitory").click(function (){
                    var istData = {
                        "area":$("#inarea").val(),
                        "buildingNo":$("#inbuildingNo").val(),
                        "buildingFloor":$("#inbuildingFloor").val(),
                        "dormSupervisorId":$("#indormSupervisorId").val(),
                        "dormitoryName":$("#indormitoryName").val(),
                        "bedNumber":$("#inbedNumber").val(),
                        "dormSupervisor":$("#indormSupervisor").val(),
                        "useStatus":$("#inuseStatus").val(),
                    }
                    $.ajax({
                        type:"post",
                        url:"/insertdormitory",
                        data:JSON.stringify(istData),
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (istData) {
                            if(istData=='1'){
                                layer.msg('添加成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(istData=='0'){
                                layer.msg('添加失败',{icon:5,time:1000},function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("添加请求失败")
                        }

                    });
                })
                break;
            case 'update':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else if(data.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                }
                break;
            case 'delete':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else {
                    layer.msg('删除');
                    $.ajax({                //批量删除
                        type:"post",
                        url:"/deleteByPkId",
                        contentType: "application/json;charset=utf-8",
                        data:JSON.stringify(json),
                        dataType:"json",
                        success:function (delData) {
                            if(delData > 0){
                                layer.msg('删除成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(delData < 1) {
                                layer.msg('删除失败', {icon: 5, time: 1000}, function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("删除请求失败");
                        }
                    })
                }
                break;
        };
    });
    //区域楼号楼层下拉框
    $.ajax({
        type:"post",
        url:"/area",
        contentType: "application/json;charset=utf-8",
        dataType:"json",
        success:function (regions) {
            var $regiones="<option value=''>请选择</option>";
            for(var i=0;i<regions.length;i++) {
                $regiones+="<option value="+regions[i].area+">"+regions[i].area+"</option>"
            }
            $("select[name='istregion']").html($regiones);

            //当select发生改变时
            $("select[name='istregion']").change(function() {
                $("#buildingNo").empty();
                if ( $("select[name='istregion'] option:selected").text() == "A") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 1;i<=5;i++){
                        var $data = $("<option >" + i + "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "B") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 6;i<=10;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "C") {
                    var $QINGXUANZE ="<option></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 11;i<=15;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "D") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 16;i<=20;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }

                }
                layui.form.render('select');
            })
            $("select[name='istbuildingNo']").change(function() {
                $("#buildingFloor").empty();
                let buildingNo = $("#buildingNo").val();
                $.get("",function(){
                    var $QINGXUANZE ="<option></option>";
                    $("#buildingFloor").append($QINGXUANZE);
                    for(let i = 1;i<=12;i++){
                        var $data = $("<option >" +i + "层</option>");
                        $("#buildingFloor").append($data);
                    }
                    layui.form.render('select');
                })
            })
        },error:function (error) {
            layer.msg("添加请求失败1");
        }
    });
    //监听行工具事件
    table.on('tool(test)', function(obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event //获得 lay-event 对应的值
            ,dropdown=layui.dropdown;
        if(layEvent === 'detail') {
            layer.msg('查看操作');
            layer.open({
                type: 1 //此处以iframe举例
                , title: data.dormitoryName + '宿舍详细信息'
                , area: ['800px', '600px']
                , shade: 0
                , maxmin: true
                , content: $("#detailedInformation")
                , success: function (layero, index) {
                        $("#stuarea").val(data.area),
                        $("#stubuildingNo").val(data.buildingNo),
                        $("#stubuildingFloor").val(data.buildingFloor),
                        $("#studormitoryName").val(data.dormitoryName),
                        $("#stubedNumber").val(data.bedNumber),
                        $("#studormSupervisorId").val(data.dormSupervisorId),
                        $("#studormSupervisor").val(data.dormSupervisor),
                        $("#stuuseStatus").val(data.useStatus);
                    $("#insertStudent").click(function () {
                        let pkId = data.pkId
                        layer.open({
                            type: 2
                            , title: '宿舍添加学生页面'
                            , area: ['1650px', '700px']
                            , shade: 0
                            , maxmin: true
                            , content: "/dormitoryFind/" + pkId
                            , success: function (layero, index) {

                            }, end: function () {

                            }
                        })
                    })
                    $("#seeStudent").click(function () {
                        let pkId = data.pkId
                        layer.open({
                            type: 2
                            , title: '宿舍查看学生页面'
                            , area: ['1550px', '700px']
                            , shade: 0
                            , maxmin: true
                            , content: "/dormitorys/" + pkId
                            , success: function (layero, index) {

                            }, end: function () {

                            }
                        })
                    })
                },end: function () {

                }
            })
        }else if(layEvent === 'more'){
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                ,show: true //外部事件触发即显示
                ,data: [{
                    title: '编辑'
                    ,id: 'edit'
                },{
                    title: '删除'
                    ,id: 'del'
                }]
                ,click: function(menudata){
                    if(menudata.id === 'del'){
                        layer.confirm('真的删除行么', function(index){
                            obj.del(); //删除对应行（tr）的DOM结构
                            //layer.close(index);
                            //向服务端发送删除指令
                            $.ajax({
                                type:'post',
                                url:"/dormitorydel",
                                data:JSON.stringify(data),
                                contentType:'application/json;charset=utf-8',
                                dataType:"json",
                                success:function (dormitory) {
                                    if(dormitory=='1'){
                                        layer.msg('删除成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(dormitory=='0'){
                                        layer.msg('删除失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    alert("请求失败")
                                }
                            })
                        });
                    }else if(menudata.id === 'edit'){
                        layer.msg('编辑操作，当前行 ID:'+ data.pkId);
                        layer.open({
                            type: 1 //此处以iframe举例
                            , title:'宿舍'+data.dormitoryName+'的信息'
                            , area: ['800px', '600px']
                            , shade: 0
                            , maxmin: true
                            ,content:$("#updatePage")
                        })
                        //数据回显
                            $("#uparea").val(data.area),
                            $("#upbuildingNo").val(data.buildingNo),
                            $("#upbuildingFloor").val(data.buildingFloor),
                            $("#updormitoryName").val(data.dormitoryName),
                            $("#upbedNumber").val(data.bedNumber),
                            $("#updormSupervisorId").val(data.dormSupervisorId),
                            $("#updormSupervisor").val(data.dormSupervisor),
                            $("#upuseStatus").val(data.useStatus);
                        $("#updatedormitory").click(function (){
                            var upDate={
                                "pkId":data.pkId,
                                "area":$("#uparea").val(),
                                "buildingFloor":$("#upbuildingFloor").val(),
                                "buildingNo":$("#upbuildingNo").val(),
                                "dormitoryName":$("#updormitoryName").val(),
                                "bedNumber":$("#upbedNumber").val(),
                                "dormSupervisorId":$("#updormSupervisorId").val(),
                                "dormSupervisor":$("#updormSupervisor").val(),
                                "useStatus":$("#upuseStatus").val(),
                            }
                            $.ajax({
                                type:"post",
                                url:"/updateByPkId",
                                data:JSON.stringify(upDate),
                                contentType: "application/json;charset=utf-8",
                                dataType:"json",
                                success:function (upDate) {
                                    if(upDate=='1'){
                                        layer.msg('修改成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(upDate=='0'){
                                        layer.msg('修改失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    layer.msg("修改请求失败")
                                }
                            })
                        })
                    }
                }
            })
        }
    })
})